//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================
#include "gsharedmem.h"
#include <aura.h>

CGhostSharedMemory::~CGhostSharedMemory()
{
    if (NULL != m_hSharedMemory) {
        AuraSharedMemory_Destroy(m_hSharedMemory);
        m_hSharedMemory = NULL;
    }
}

ECode CGhostSharedMemory::Initialize(
            /* [in] */ WString name,
            /* [in] */ MemorySize size,
            /* [in] */ Boolean bCommit)
{
    assert(!name.IsNullOrEmpty());

    if (0 == size) {
        return E_INVALID_ARGUMENT;
    }

    return (ECode)AuraSharedMemory_Create((Aura_PWChar)(const wchar_t *)name,
                                (Aura_MemorySize)size,
                                (Aura_Bool)bCommit,
                                AURA_FALSE,
                                &m_hSharedMemory);
}

UInt32 CGhostSharedMemory::AddRef(void)
{
    Int32 nRefs = m_nRefs.Increment();
    return (UInt32)nRefs;
}

UInt32 CGhostSharedMemory::Release(void)
{
    Int32 nRefs = m_nRefs.Decrement();

    if (0 == nRefs) {
        GhostFactory factory(this->GetOid());
        Ghost::S_DeleteGhost(&factory, this);
        delete this;
    }

    return (UInt32)nRefs;
}

ECode CGhostSharedMemoryFactory::CreateGhost(
        /* [out] */ Ghost ** ppGhost,
        /* [out] */ Boolean * pbExisted)
{
    CGhostSharedMemory * pGhost = NULL;
    ECode ec = NOERROR;

    assert(NULL != ppGhost);
    assert(NULL == pbExisted);

    pGhost = new CGhostSharedMemory();
    if (NULL == pGhost) {
        ec = E_OUT_OF_MEMORY;
        goto ErrorExit;
    }
    ec = pGhost->Initialize(this->GetName(), m_size, m_bCommit);
    if (FAILED(ec)) {
        goto ErrorExit;
    }
    pGhost->AddRef();
    *ppGhost = pGhost;

    return ec;

ErrorExit:
    if (NULL != pGhost) {
        delete pGhost;
    }
    return ec;
}

